import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../routes/app_pages.dart';
import '../../../services/user_utils.dart';
import '../../../services/utils.dart';

class MineController extends GetxController {
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 退出登录
  Future<void> logout() async {
    try {
      // 显示确认对话框
      final result = await Get.dialog<bool>(
        AlertDialog(
          title: const Text('提示'),
          content: const Text('确定要退出登录吗？'),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text(
                '确定',
                style: TextStyle(color: Colors.red),
              ),
            ),
          ],
        ),
      );

      if (result == true) {
        SmartDialog.showLoading(msg: "正在退出...");

        // 清空用户信息
        await UserUtils.logout();

        myLog('用户已退出登录');

        SmartDialog.dismiss();
        SmartDialog.showToast(
          '已退出登录',
          alignment: Alignment.center,
        );

        // 跳转到登录页面，清除所有页面栈
        Get.offAllNamed(Routes.LOGIN);
      }
    } catch (e) {
      SmartDialog.dismiss();
      myLog('退出登录失败: $e');
      SmartDialog.showToast(
        '退出登录失败: $e',
        alignment: Alignment.center,
      );
    }
  }
}
